package com.citai.tool;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class Application {
	public static void main(String[] args) throws IOException {
		if(args != null) {
			
			if(args.length == 1) {
				String ret = convertString(args[0]);
				System.out.println(ret);
			}else if(args.length > 1 && "-f".equalsIgnoreCase(args[0])) {
				String path = args[1];
				String ret = convertPath(path);
				System.out.println("转换后文件路径：" + ret);
			}
		}else {
			usage();
		}
	}
	
	private static void usage() {
		System.out.println("java -jar hanziToPinyin.jar \"你好，中国！\"");
		System.out.println("java -jar hanziToPinyin.jar -f text.txt");
		System.out.println("java -jar hanziToPinyin.jar -f d:\temp\text.txt");
	}
	
	private static String convertString(String source) {
		if(source == null || "".equals(source.trim())) {
			System.out.println("要转换的内容不能为空！");
			usage();
			return null;
		}
		return Utils.toHanyuPinyinAcronym(source);
	}
	
	private static String convertPath(String path) throws IOException {
		File f = new File(path);
		if(!f.exists()) {
			System.out.println("要转换的文件不存在！路径：" + f.getAbsolutePath());
			usage();
			return null;
		}
		
		StringBuffer sb = new StringBuffer();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
			String line = null;
			while((line = br.readLine()) != null) {
				sb.append(Utils.toHanyuPinyinAcronym(line)).append(System.lineSeparator());
			}
		}  finally {
			if(br != null) {
				br.close();
			}
		}
		BufferedWriter wr = null;
		File out;
		try {
			out = new File(f.getAbsoluteFile() + "2.txt");
			wr = new BufferedWriter(new FileWriter(out));
			wr.write(sb.toString());
		} finally {
			wr.close();
		}
		
		return out.getAbsolutePath();
	}
}
